/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */

package com.hopes.bizz.risk.control.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopes.bizz.risk.control.dto.RiskObjectDTO;
import com.hopes.bizz.risk.control.dto.RiskObjectExcelDTO;
import com.hopes.bizz.risk.control.entity.RiskObjectEntity;
import com.hopes.bizz.risk.control.service.RiskObjectService;
import com.hopes.bizz.risk.control.service.RiskUnitService;
import com.hopes.bizz.risk.control.vo.RiskObjectExcelVO;
import com.hopes.bizz.risk.control.vo.RiskObjectVO;
import com.hopes.boss.admin.api.resolver.DictResolver;
import com.hopes.boss.common.core.exception.BizException;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.excel.annotation.RequestExcel;
import com.hopes.boss.common.excel.annotation.ResponseExcel;
import com.hopes.boss.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 风险分析对象
 *
 * @author daijie
 * @date 2023-07-17 17:01:16
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/riskObject" )
@Tag(description = "RiskObject" , name = "风险分析对象管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class RiskObjectController {

    private final RiskObjectService riskObjectService;

    private final RiskUnitService riskUnitService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param riskObject 风险分析对象
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('control_risk_object_view')" )
    public R getRiskObjectPage(Page page, RiskObjectEntity riskObject) {
        LambdaQueryWrapper<RiskObjectEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotNull(riskObject.getHazardType()), RiskObjectEntity::getHazardType, riskObject.getHazardType());
        wrapper.eq(ObjectUtil.isNotNull(riskObject.getRiskLevel()), RiskObjectEntity::getRiskLevel, riskObject.getRiskLevel());
        wrapper.eq(StringUtil.isNotBlank(riskObject.getControlLevel()), RiskObjectEntity::getControlLevel, riskObject.getControlLevel());
        wrapper.eq(ObjectUtil.isNotNull(riskObject.getHazardSourceFlag()), RiskObjectEntity::getHazardSourceFlag, riskObject.getHazardSourceFlag());
        wrapper.eq(ObjectUtil.isNotNull(riskObject.getHazardSourceLevel()), RiskObjectEntity::getHazardSourceLevel, riskObject.getHazardSourceLevel());
        wrapper.like(StringUtil.isNotBlank(riskObject.getDeptId()), RiskObjectEntity::getDeptId, riskObject.getDeptId());

        Page pageInfo = riskObjectService.page(page, wrapper);
        List<RiskObjectVO> voList = new ArrayList<>();
        for (Object record : pageInfo.getRecords()) {
            RiskObjectVO vo = new RiskObjectVO();
            BeanUtils.copyProperties(record, vo);
            Integer num = riskUnitService.getCountLByRiskObjectId(vo.getId());
            vo.setRiskUnitNum(num);
            voList.add(vo);
        }
        pageInfo.setRecords(voList);
        return R.ok(pageInfo);
    }

    /**
     * 通过id查询风险分析对象
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('control_risk_object_view')" )
    public R getById(@PathVariable("id" ) String id) {
        RiskObjectEntity entity = riskObjectService.getById(id);
        RiskObjectVO vo = new RiskObjectVO();
        BeanUtils.copyProperties(entity, vo);
        return R.ok(vo);
    }

    /**
     * 新增风险分析对象
     * @param dto 风险分析对象dto
     * @return R
     */
    @Operation(summary = "新增风险分析对象" , description = "新增风险分析对象" )
    @SysLog("新增风险分析对象" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('control_risk_object_add')" )
    @CacheEvict(value = DictResolver.CACHE_NAME_DICT, allEntries = true)
    public R save(@RequestBody RiskObjectDTO dto) {
        return R.ok(riskObjectService.save(dto.toPO()));
    }

    /**
     * 修改风险分析对象
     * @param dto 风险分析对象dto
     * @return R
     */
    @Operation(summary = "修改风险分析对象" , description = "修改风险分析对象" )
    @SysLog("修改风险分析对象" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('control_risk_object_edit')" )
    @CacheEvict(value = DictResolver.CACHE_NAME_DICT, allEntries = true)
    public R updateById(@RequestBody RiskObjectDTO dto) {
        return R.ok(riskObjectService.updateById(dto.toPO()));
    }

    /**
     * 通过id删除风险分析对象
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除风险分析对象" , description = "通过id删除风险分析对象" )
    @SysLog("通过id删除风险分析对象" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('control_risk_object_del')" )
    @CacheEvict(value = DictResolver.CACHE_NAME_DICT, allEntries = true)
    public R removeById(@RequestBody Long[] ids) {
        if (ids.length == 0) {
            return null;
        }
        for (Long id : ids) {
            Integer num = riskUnitService.getCountLByRiskObjectId(id);
            if (num > 0) {
                throw new BizException("请先删除绑定风险分析单元!");
            }
        }

        return R.ok(riskObjectService.removeBatchByIds(CollUtil.toList(ids)));
    }

    /**
     * excel模板
     *
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/template")
    @PreAuthorize("@pms.hasPermission('control_risk_object_export')")
    public List<RiskObjectExcelVO> template() {
        return riskObjectService.exportExcel(Arrays.asList(new RiskObjectEntity()));
    }

    /**
     * 导出excel 表格
     * @param riskObject 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('control_risk_object_export')")
    public List<RiskObjectExcelVO> export(RiskObjectEntity riskObject) {
        LambdaQueryWrapper<RiskObjectEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotNull(riskObject.getHazardType()), RiskObjectEntity::getHazardType, riskObject.getHazardType());
        wrapper.eq(ObjectUtil.isNotNull(riskObject.getRiskLevel()), RiskObjectEntity::getRiskLevel, riskObject.getRiskLevel());
        wrapper.eq(StringUtil.isNotBlank(riskObject.getControlLevel()), RiskObjectEntity::getControlLevel, riskObject.getControlLevel());
        wrapper.eq(ObjectUtil.isNotNull(riskObject.getHazardSourceFlag()), RiskObjectEntity::getHazardSourceFlag, riskObject.getHazardSourceFlag());
        wrapper.eq(ObjectUtil.isNotNull(riskObject.getHazardSourceLevel()), RiskObjectEntity::getHazardSourceLevel, riskObject.getHazardSourceLevel());
        wrapper.like(StringUtil.isNotBlank(riskObject.getDeptId()), RiskObjectEntity::getDeptId, riskObject.getDeptId());

        return riskObjectService.exportExcel(riskObjectService.list(wrapper));
    }

    /**
     * 导入excel 表格
     * @param riskObjectExcelDtoList 查询条件
     * @param bindingResult 错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @PreAuthorize("@pms.hasPermission('control_risk_object_export')")
    public R importExcel(@RequestExcel List<RiskObjectExcelDTO> riskObjectExcelDtoList, BindingResult bindingResult) {
        if (riskObjectExcelDtoList.size() == 1 && riskObjectExcelDtoList.get(0).getHazardName() == null) {
            throw new BizException("内容为空，不可导入");
        }
        return riskObjectService.importExcel(riskObjectExcelDtoList, bindingResult);
    }
}